package com.xiaoxu.gateway.filter;

import com.xiaoxu.spzx.model.entity.user.UserInfo;
import com.xiaoxu.spzx.model.vo.common.Result;
import com.xiaoxu.spzx.model.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import com.alibaba.fastjson.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    //*********************网关过滤器 ，统一处理会员登录
    @Autowired
    private RedisTemplate<String , String> redisTemplate;
    //路径匹配规则
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求的路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //判断路径 是否满足规则
        if (antPathMatcher.match("/api/**/auth/**",path)){
            //登录校验
            UserInfo userInfo = this.getUserInfo(request);
            if (userInfo == null){
                ServerHttpResponse response = exchange.getResponse();
                //未登录
                return out(response,ResultCodeEnum.LOGIN_AUTH);
            }
            //判断是否登录
        }

        return chain.filter(exchange);
    }
    private UserInfo getUserInfo(ServerHttpRequest request) {
            //获取请求头中的token
            String token = "";
            List<String> tokenList = request.getHeaders().get("token");
            if (tokenList != null){
                token = tokenList.get(0);
            }
            //判断token为空
        if (StringUtils.hasText(token)){
            //从redis中获取用户信息
            String userInfo = redisTemplate.opsForValue().get("user:login" + token);
            if (StringUtils.hasText(userInfo)){
                return JSONObject.parseObject(userInfo, UserInfo.class);
            }
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
